package org.jeecg.magic.config;

import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.context.RequestEntity;
import org.ssssssss.magicapi.core.interceptor.ResultProvider;
import org.ssssssss.magicapi.modules.db.model.Page;
import org.ssssssss.script.exception.MagicScriptException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Mark.Chen
 * @description: 自定义返回
 * @date 2022-6-2 19:38
 */
@Component
public class MagicApiResultProvider implements ResultProvider {

    @Override
    public Object buildResult(RequestEntity requestEntity, int code, String message, Object data) {
        return new HashMap<String,Object>(){{
            //0成功,1失败
            put("status", code>0?1:0);
            put("msg", message);
            put("data", data==null? new HashMap<>() :data);
        }};
    }

    @Override
    public Object buildPageResult(RequestEntity requestEntity, Page page, long total, List<Map<String, Object>> data) {
        return new HashMap<String,Object>(){{
            put("total", total);
            put("items", data==null?new ArrayList<>():data);
        }};
    }


    @Override
    public Object buildException(RequestEntity requestEntity, Throwable throwable) {
        String message = "系统内部出现错误";
        if(throwable instanceof MagicScriptException){
            message+= "："+((MagicScriptException)throwable).getSimpleMessage();
        }
        return buildResult(requestEntity, 500, message);
    }
}
